<script setup lang="ts">
import { ElRow, ElCol, ElAlert, ElDialog } from "element-plus";
import { ref, onMounted, onUnmounted, watch } from "vue";
import "codemirror/mode/javascript/javascript.js";
import type { CmComponentRef } from "codemirror-editor-vue3";
import { DocumentEditor } from "@onlyoffice/document-editor-vue";
import { el } from "element-plus/es/locales.mjs";
const scriptUrl = defineModel("scriptUrl");
const demoFileUrl = defineModel("demoFileUrl");
const demoConfigType = defineModel("demoConfigType");
const demoConfigMode = defineModel("demoConfigMode");
interface Props {
  scriptUrl?: string;
}

defineOptions({
  name: "Compare",
});

const props = withDefaults(defineProps<Props>(), {});

const getUuid = function () {
  return "xxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

const VITE_ONLY_OFFICE_BASE_URL = import.meta.env.VITE_ONLY_OFFICE_BASE_URL;
const code = ref(``);
const containerRef = ref();
const cmRef = ref<CmComponentRef>();

let documentEditorKey = ref("");
let containerHeight = 0;
let officeHeight = ref("100%");
let doHeight = ref(false);
onMounted(() => {
  containerHeight = containerRef.value.parentNode.offsetHeight;
  console.log(11, containerHeight);
  containerRef.value.style.height = containerHeight + "px";
  if (containerHeight > 800) {
    containerHeight = 800;
  }
  officeHeight.value = containerHeight + "px";
  doHeight.value = true;
  documentEditorKey.value = getUuid();
});

onUnmounted(() => {
  cmRef.value?.destroy();
});

watch(demoFileUrl, async (newsDemoFileUrl, oldDemoFileUrl) => {});

let sourceConnector = null;
let targetConnector = null;
let sourceTextLine = [];
let targetTextLine = [];
let sourceDone = false;
let targetDone = false;
const onDocumentReadySource = () => {
  sourceConnector = DocEditor.instances.source.createConnector();
  drawSource();
  // sourceConnector.callCommand(
  //   function () {
  //     var oDocument = Api.GetDocument();
  //     var allParagraphs = oDocument.GetAllParagraphs();
  //     let sourceTextLine = [];
  //     for (var i = 0; i < allParagraphs.length; i++) {
  //       sourceTextLine.push(allParagraphs[i].GetText());
  //     }
  //     return sourceTextLine;
  //   },
  //   function (data) {
  //     sourceTextLine = data;
  //     sourceDone = true;
  //   }
  // );
};
const onDocumentReadyTarget = () => {
  targetConnector = DocEditor.instances.target.createConnector();
  drawTarget();
  // targetConnector.callCommand(
  //   function () {
  //     var oDocument = Api.GetDocument();
  //     var allParagraphs = oDocument.GetAllParagraphs();
  //     let targetTextLine = [];
  //     for (var i = 0; i < allParagraphs.length; i++) {
  //       targetTextLine.push(allParagraphs[i].GetText());
  //     }
  //     return targetTextLine;
  //   },
  //   function (data) {
  //     targetTextLine = data;
  //     targetDone = true;
  //   }
  // );
};

let drawSource = function () {
  cleanContent(sourceConnector);
  Asc.scope = {
    compareResult: compareResult,
  };
  sourceConnector.callCommand(
    function () {
      Api.CleanDocToPure();
      Api.startFixRangePos();
      var resultMap = {};
      for (var i = 0; i < Asc.scope.compareResult.length; i++) {
        var item = Asc.scope.compareResult[i];
        if (!resultMap[item["posDoc1"]["pIndex"]]) {
          // pIndex可能会被后端处理为pindex，请注意
          resultMap[item["posDoc1"]["pIndex"]] = [];
        }
        if (item["type"] == "DELETION") {
          // pIndex可能会被后端处理为pindex，请注意
          resultMap[item["posDoc1"]["pIndex"]].push(item);
        }
      }
      var oDocument = Api.GetDocument();
      oDocument.OpenViewEdit();
      setTimeout(() => {
        var allParagraphs = oDocument.GetAllParagraphs();
        for (var i = 0; i < allParagraphs.length; i++) {
          if (resultMap[i] != undefined) {
            for (var j = 0; j < resultMap[i].length; j++) {
              if (resultMap[i][j]["type"] == "DELETION") {
              }
              var startPos = resultMap[i][j]["posDoc1"]["startPos"];
              var endPos = resultMap[i][j]["posDoc1"]["endPos"];
              if(startPos == endPos && startPos == 0){
                var para = allParagraphs[Math.max(0, i-1)];
                para.SetStrikeout(true);
                para.SetColor(255, 255, 255);
                para.SetHighlight("red");
              }else{
                allParagraphs[i].GetRange(startPos, endPos).SetStrikeout(true);
                allParagraphs[i].GetRange(startPos, endPos).SetColor(255, 255, 255);
                allParagraphs[i].GetRange(startPos, endPos).SetHighlight("red");
              }
            }
          }
        }
        oDocument.CloseViewEdit();
        Api.endFixRangePos();
      }, 100);
    },
    function () {}
  );
};

let drawTarget = function () {
  cleanContent(targetConnector);
  Asc.scope = {
    compareResult: compareResult,
  };
  targetConnector.callCommand(
    function () {
      Api.CleanDocToPure();
      Api.startFixRangePos();
      var resultMap = {};
      for (var i = 0; i < Asc.scope.compareResult.length; i++) {
        var item = Asc.scope.compareResult[i];
        if (item["type"] == "ADDITION") {
          // pIndex可能会被后端处理为pindex，请注意
          resultMap[item["posDoc2"]["pIndex"]] = item;
        }
      }

      var oDocument = Api.GetDocument();
      oDocument.OpenViewEdit();
      setTimeout(() => {
        var allParagraphs = oDocument.GetAllParagraphs();
        for (var i = 0; i < allParagraphs.length; i++) {
          if (resultMap[i] != undefined) {
            if (resultMap[i]["type"] == "ADDITION") {
              var startPos = resultMap[i]["posDoc2"]["startPos"];
              var endPos = resultMap[i]["posDoc2"]["endPos"];
              if(startPos == endPos && startPos == 0){
                allParagraphs[i].SetColor(255, 255, 255);
                allParagraphs[i].SetHighlight("blue");
              }else{
                allParagraphs[i].GetRange(startPos, endPos).SetColor(255, 255, 255);
                allParagraphs[i].GetRange(startPos, endPos).SetHighlight("blue");
              }
            }
          }
        }
        oDocument.CloseViewEdit();
        Api.endFixRangePos();
      }, 100);
    },
    function () {}
  );
};

let cleanContent = function (connector) {
  return;
  connector.callCommand(
    function () {
      var oDocument = Api.GetDocument();
      var allParagraphs = oDocument.GetAllParagraphs();
      var aComments = oDocument.GetAllComments();
      for (var i = 0; i < aComments.length; i++) {
        var ele = aComments[i];
        ele.Delete();
      }
      var aBookmarks = oDocument.GetAllBookmarksNames();
      var sNames = [];
      for (var i = 0, nCount = aBookmarks; i < nCount; i++) {
        sNames.push(aBookmarks[i]);
        
      }
      for(var i=0;i<sNames.length;i++){
        oDocument.DeleteBookmark(sNames[i]);
      }

      for (
        var paraIndex = 0;
        paraIndex < allParagraphs.length;
        paraIndex++
      ) {
        var paraRange = allParagraphs[paraIndex].GetRange();
        paraRange.SetHighlight('none');
        paraRange.SetItalic(false);
        paraRange.SetColor(0,0,0);
        paraRange.SetBold(false);
        var curPara = allParagraphs[paraIndex].Paragraph;

        var paraContent = curPara.Content;
        
        for (
          var contentIndex = 0;
          contentIndex < paraContent.length;
          contentIndex++
        ) {
          var paraEle = paraContent[contentIndex];
          if (paraEle.Type === 48) {
            // 超链接
            var hyperlinkProterty = new window.Asc.CHyperlinkProperty({
              Text: null,
              Value: paraEle.Value,
              ToolTip: paraEle.ToolTip,
              Class: paraEle,
            });
            Api.remove_Hyperlink(hyperlinkProterty);
            
          }
        }
      }
    },
    function (data) {}
  );
};

let jumpDiff = function(item){
  Asc.scope = {
    jumpPara: 0,
  };
  if(item["type"] == "DELETION"){
    Asc.scope.jumpPara = item["posDoc1"]["pIndex"];
  }
  if(item["type"] == "ADDITION"){
    Asc.scope.jumpPara = item["posDoc2"]["pIndex"];
  }
  let jumpTo = function(connector){
    connector.callCommand(
      function () {
        var oDocument = Api.GetDocument();
        var allParagraphs = oDocument.GetAllParagraphs();
        if(allParagraphs.length >= Asc.scope.jumpPara){
          allParagraphs[Asc.scope.jumpPara].GetRange(0, 1).ScrollTo();
        }else{
          allParagraphs[allParagraphs.length-1].GetRange(0, 1).ScrollTo();
        }
      },
      function () {}
    );
  };
  jumpTo(sourceConnector);
  jumpTo(targetConnector);
}

var sourceConfig = ref({
  height: officeHeight.value,
  type: "desktop",
  // "type": "mobile",
  documentType: "word",
  historyList: {
    history: [],
    currentVersion: "1",
  },
  document: {
    title: "source.docx",
    url: "http://47.94.91.67/demo_file/comment_test.docx",
    permissions: {
      print: true,
      download: true,
      edit: true,
    },
    fileType: "docx",
    key: getUuid(),
  },
  editorConfig: {
    customization: {
      autosave: false,
      compactToolbar: false,
      forcesave: true,
      toolbarNoTabs: true,
      help: false,
      compactHeader: false,
      hideRightMenu: true,
      plugins: true,
      uiTheme: "theme-light",
      zoom: 70,
      toolbar: false,
      leftMenu: false,
    },
    mode: "view",
    callbackUrl:
      "https://api.docs.onlyoffice.com/dummyCallback",
    lang: "zh-CN",
    user: {
      name: "曹瑞剑雄",
      id: "104",
    },
  },
});

var targetConfig = ref({
  height: officeHeight.value,
  type: "desktop",
  // "type": "mobile",
  documentType: "word",
  historyList: {
    history: [],
    currentVersion: "1",
  },
  document: {
    title: "target.docx",
    url: "http://47.94.91.67/demo_file/comment_test_2.docx",
    permissions: {
      print: true,
      download: true,
      edit: true,
    },
    fileType: "docx",
    key: getUuid(),
  },
  editorConfig: {
    customization: {
      autosave: false,
      compactToolbar: false,
      forcesave: true,
      toolbarNoTabs: true,
      help: false,
      compactHeader: false,
      hideRightMenu: true,
      plugins: true,
      uiTheme: "theme-light",
      zoom: 70,
      toolbar: false,
      leftMenu: false,
    },
    mode: "view",
    callbackUrl:
      "https://api.docs.onlyoffice.com/dummyCallback",
    lang: "zh-CN",
    user: {
      name: "曹瑞剑雄",
      id: "104",
    },
  },
});

var compareResult = [
  {
    type: "ADDITION",
    text: "新增",
    posDoc1: {
      pIndex: 0,
      startPos: 0,
      endPos: 0,
    },
    posDoc2: {
      pIndex: 0,
      startPos: 3,
      endPos: 5,
    },
  },
  {
    type: "DELETION",
    text: "务发",
    posDoc1: {
      pIndex: 5,
      startPos: 4,
      endPos: 6,
    },
    posDoc2: {
      pIndex: 0,
      startPos: 0,
      endPos: 0,
    },
  },
  {
    type: "DELETION",
    text: "乙方",
    posDoc1: {
      pIndex: 5,
      startPos: 23,
      endPos: 25,
    },
    posDoc2: {
      pIndex: 0,
      startPos: 0,
      endPos: 0,
    },
  },
  {
    type: "ADDITION",
    text: "新增几个字",
    posDoc1: {
      pIndex: 0,
      startPos: 0,
      endPos: 0,
    },
    posDoc2: {
      pIndex: 5,
      startPos: 24,
      endPos: 29,
    },
  },
  {
    type: "DELETION",
    text: "规正确为甲方办理相",
    posDoc1: {
      pIndex: 36,
      startPos: 23,
      endPos: 32,
    },
    posDoc2: {
      pIndex: 0,
      startPos: 0,
      endPos: 0,
    },
  },
  {
    type: "ADDITION",
    text: "新增自然段",
    posDoc1: {
      pIndex: 0,
      startPos: 0,
      endPos: 0,
    },
    posDoc2: {
      pIndex: 37,
      startPos: 0,
      endPos: 0,
    },
  },
  {
    type: "DELETION",
    text: "户名 ：重顾问有限公司；",
    posDoc1: {
      pIndex: 42,
      startPos: 0,
      endPos: 0,
    },
    posDoc2: {
      pIndex: 0,
      startPos: 0,
      endPos: 0,
    },
  },
];

const init = function () {
  sourceConfig.value.document.key = getUuid();
};
init();

const dialogVisible = ref(true);
</script>

<template>
  <di class="onlyoffice_demo_container" ref="containerRef">
    <el-dialog v-model="dialogVisible" show-close="false">
      <el-row style="height: 60px">
        <el-col :span="24">
          <el-alert
            style="
              height: 30px;
              font-size: 15px;
              font-weight: 600;
            "
            title="该功能为简单实现，如果文档很大或者数据量很大，请寻找专业比对工具代替"
            type="error"
            closable="false"
          />
          <el-alert
            style="
              height: 30px;
              font-size: 15px;
              font-weight: 600;
            "
            title="文档比对功能分为：前端展示+后端比对，目前仅出售【前端展示】功能"
            type="error"
            closable="false"
          />
          <el-alert
            style="
              height: 30px;
              font-size: 15px;
              font-weight: 600;
            "
            title="高级版本用户可向我们咨询后端使用到技术，以方便自行实现"
            type="error"
            closable="false"
          />
        </el-col>
      </el-row>
    </el-dialog>
    
    <el-row style="height: 100%">
      <el-col :span="10">
        <DocumentEditor
          v-if="doHeight"
          id="source"
          :documentServerUrl="VITE_ONLY_OFFICE_BASE_URL"
          :config="sourceConfig"
          :events_onDocumentReady="onDocumentReadySource"
        />
      </el-col>
      <el-col :span="10" style="height: 100%">
        <DocumentEditor
          v-if="doHeight"
          id="target"
          :documentServerUrl="VITE_ONLY_OFFICE_BASE_URL"
          :config="targetConfig"
          :events_onDocumentReady="onDocumentReadyTarget"
        />
      </el-col>
      <el-col :span="4">
        <div class="flex-col diff-panel">
          <div class="flex-row panel-title main-align-space-between">
            <div class="flex-row cross-align-center">
              <div class="flex-row title bold">
                差异项（{{ compareResult.length }}）
              </div>
            </div>
            <div class="icon-moves">
              <i class="iconshouqi-yuan mr-12"></i
              ><i class="iconzhankai-yuan activation"></i>
            </div>
          </div>
          <div class="flex-col panel-body">
            <template v-for="item in compareResult">
              <div
                v-if="item.type == 'ADDITION'"
                class="flex-col diff-item diff-item-addition diff-item-active"
                @click="jumpDiff(item)"
              >
                <div class="flex-row cross-align-center bold">
                  <div class="flex-row diff-dot"></div>
                  <div class="flex-row diff-type bold">添加</div>
                </div>
                <div class="diff-content">
                  <span class="addition">{{ item.text }}</span>
                </div>
              </div>
              <div
                v-if="item.type == 'DELETION'"
                class="flex-col diff-item diff-item-deletion"
                @click="jumpDiff(item)"
              >
                <div class="flex-row cross-align-center bold">
                  <div class="flex-row diff-dot"></div>
                  <div class="flex-row diff-type bold">删除</div>
                </div>
                <div class="diff-content">
                  <span class="deletion">{{ item.text }}</span>
                </div>
              </div>
            </template>
          </div>
        </div>
      </el-col>
    </el-row>
  </di>
</template>

<style scoped>
.onlyoffice_demo_container {
  width: 100%;
  height: 100%;
  display: inline-block;
}
.panel-title {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 6px;
  padding: 0 24px;
}
.cross-align-center {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.diff-panel-list .title {
  font-size: 16px;
}
.panel-body {
  padding: 0 24px;
  overflow: auto;
}
.diff-item {
  border: 1px solid rgba(81, 141, 150, 0.2);
  border-radius: 4px;
  margin-top: 12px;
  cursor: pointer;
  padding: 6px 10px 15px;
  background: rgba(232, 234, 239, 0.21);
  border: 1px solid rgba(185, 192, 206, 0.3);
  border-radius: 8px;
}
.diff-item-active {
  border: 1px solid #1c6dff;
  -webkit-box-shadow: 0 0 16px 6px rgba(57, 127, 138, 0.1215686275);
  box-shadow: 0 0 16px 6px rgba(57, 127, 138, 0.1215686275);
}
.cross-align-center {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.bold {
  font-weight: 500;
}
.diff-dot {
  width: 2px;
  height: 14px;
  background: #00bfaf;
  margin-right: 8px;
}
.diff-item-addition .diff-dot {
  background: #1c6dff;
}
.diff-type {
  color: #2f3d59;
}
.diff-content {
  word-break: break-all;
  white-space: break-spaces;
}
.diff-content {
  padding-left: 10px;
  margin-top: 10px;
  line-height: 22px;
  max-height: 154px;
  overflow-y: hidden;
}
.diff-item-deletion .diff-dot,
.diff-item-unfill .diff-dot {
  background: #ec4949;
}
.flex-row {
  -webkit-box-orient: horizontal;
  -ms-flex-direction: row;
  flex-direction: row;
}
.flex-col {
  -webkit-box-orient: vertical;
  -ms-flex-direction: column;
  flex-direction: column;
}
.flex-col,
.flex-row {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-direction: normal;
}
.diff-content .addition {
  color: #1c6dff;
}
.diff-content .deletion {
  color: #ec4949;
  text-decoration: line-through;
}
</style>
